package net.lzzy.lxq.config;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

//@ServerEndpoint("/socket/{id}")
//@Component
public class WebSocketServer {

    public String token="hello";

    private Session session;

    @OnOpen
    public void onOpen(@PathParam("id")int id,Session session) throws IOException {
        this.session=session;
        System.out.println("有连接："+id);
        if (session.isOpen()){
            System.out.println("opened，id="+session.getId());
            echo();
        }else{
            System.out.println("failed");
        }
    }

    public void echo() throws IOException {
        this.session.getBasicRemote().sendText("连接成功，你的id="+this.session.getId());
    }

    public void sendMessage(String text) throws IOException {
        this.session.getBasicRemote().sendText(text);
    }

    @OnMessage
    public void onMessage(String text) throws IOException {
        System.out.println("收到消息"+text);
        sendMessage("你发送的消息是："+text);
    }

    @OnClose
    public void onClose(){
        System.out.println("关闭消息");
    }
}
